package com.tim.app.ui.activity.selected;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.application.library.log.DLOG;
import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.event.EventListener;
import com.application.library.runtime.event.EventManager;
import com.application.library.util.ClickUtil;
import com.application.library.util.KeyboardChangeListener;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.tim.app.R;
import com.tim.app.RT;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.manager.ImagePickerManager;
import com.tim.app.server.api.API_App;
import com.tim.app.server.api.API_Found;
import com.tim.app.server.api.API_Statistics;
import com.tim.app.server.entry.Answer;
import com.tim.app.server.entry.InputContent;
import com.tim.app.server.entry.Problem;
import com.tim.app.server.entry.User;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.server.result.UploadResult;
import com.tim.app.ui.activity.BaseActivity;
import com.tim.app.ui.view.LSWebView;
import com.tim.app.ui.widget.imagepick.bean.ImageItem;
import com.tim.app.util.SoftKeyboardUtil;
import com.tim.app.util.ToastUtil;

import java.util.ArrayList;

import static com.tim.app.constant.AppKey.REQUEST_CODE_PROBLEM_TILTE;

/**
 * 富文本编辑器
 */
public class AnswerActivity extends BaseActivity implements KeyboardChangeListener.KeyBoardListener {

    private static final String TAG = "AnswerActivity";

    private TextView tvSend;
    private ImageButton ibKeyboard, ib_picture, ibAt;
    private ImagePickerManager imagePicker;
    private LSWebView lsContent;
    private ImageButton ibBack;
    private ImageButton ibSetting;

    private TextView tvBack;

    private boolean isEditAnswer;//编辑回答
    private boolean isEditProblem;//编辑问题

    private Answer answer;
    private Problem problem;

    private boolean isAnswer;
    private String questionTitle;
    private String questionId;

    private LinearLayout llActionBottom;
    private TextView tvAnonymousState;
    private ImageButton ibAnonymous;
    private boolean isAnonymous = false;

    private KeyboardChangeListener mKeyboardChangeListener;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_answer;
    }

    /**
     * 编辑回答
     *
     * @param context
     * @param data
     */
    public static void startWithEditAnswer(Context context, Answer data) {
        Intent intent = new Intent(context, AnswerActivity.class);
        intent.putExtra(AppKey.ANSWER, data);
        intent.putExtra("isEditAnswer", true);
        context.startActivity(intent);
    }

    /**
     * 编辑问题
     *
     * @param context
     * @param data
     */
    public static void startWithEditProblem(Activity context, Problem data) {
        Intent intent = new Intent(context, AnswerActivity.class);
        intent.putExtra(AppKey.PROBLEM, data);
        intent.putExtra("isEditProblem", true);
        context.startActivityForResult(intent, REQUEST_CODE_PROBLEM_TILTE);
    }

    @Override
    public void initView() {
        lsContent = (LSWebView) findViewById(R.id.lsContent);
        tvSend = (TextView) findViewById(R.id.tvSend);
        ib_picture = (ImageButton) findViewById(R.id.ib_picture);
        ibKeyboard = (ImageButton) findViewById(R.id.ibKeyboard);
        ibAt = (ImageButton) findViewById(R.id.ibAt);
        tvBack = (TextView) findViewById(R.id.tvBack);
        ibBack = (ImageButton) findViewById(R.id.ibBack);
        ibSetting = (ImageButton) findViewById(R.id.ibSetting);
        llActionBottom = (LinearLayout) findViewById(R.id.llActionBottom);
        tvAnonymousState = (TextView) findViewById(R.id.tvAnonymousState);
        ibAnonymous = (ImageButton) findViewById(R.id.ibAnonymous);

        ibSetting.setOnClickListener(this);
        ibAnonymous.setOnClickListener(this);
        ibKeyboard.setOnClickListener(this);
        ibBack.setOnClickListener(this);
        tvBack.setOnClickListener(this);
        ibAt.setOnClickListener(this);

        tvSend.setOnClickListener(this);
        ib_picture.setOnClickListener(this);
        imagePicker = ImagePickerManager.ins();
        imagePicker.setMultiMode(false);
        imagePicker.setCrop(false);
        if (android.os.Build.MODEL.contains("HM NOTE")) {
            imagePicker.setShowCamera(false);
        }

        mKeyboardChangeListener = new KeyboardChangeListener(this);
        mKeyboardChangeListener.setKeyBoardListener(this);
        EventManager.ins().registListener(EventTag.ON_AT, eventListener);
        EventManager.ins().registListener(EventTag.ON_GET_CONTENT, eventListener);
        EventManager.ins().registListener(EventTag.ON_PROBLEM_ADD, eventListener);

        lsContent.loadUrl("https://www.urmoli.com/webHtml/ml_editor/editor.html");
        lsContent.setFocusableInTouchMode(true);
        lsContent.requestFocus();
        lsContent.setFocusable(true);
        SoftKeyboardUtil.showSoftKeyboard(lsContent);

        if (getIntent().hasExtra("isEditAnswer")) {
            isAnswer = true;
            isEditAnswer = getIntent().getBooleanExtra("isEditAnswer", false);
            answer = (Answer) getIntent().getSerializableExtra(AppKey.ANSWER);
            String content = answer.getContent();
            lsContent.loadUrl("javascript:htmls('" + content + "')");
            isAnonymous = answer.getIsAnonymous() == 1 ? true : false;
            updateAnonymousUI();
        } else if (getIntent().hasExtra("isEditProblem")) {
            isAnswer = false;
            isEditProblem = getIntent().getBooleanExtra("isEditProblem", false);
            problem = (Problem) getIntent().getSerializableExtra(AppKey.PROBLEM);
            String content = problem.getContent();
            lsContent.loadUrl("javascript:htmls('" + content + "')");
            isAnonymous = problem.getIsAnonymous() == 1 ? true : false;
            updateAnonymousUI();
        } else {
            if (getIntent().hasExtra(AppKey.IS_ANSWER)) {
                isAnswer = getIntent().getBooleanExtra(AppKey.IS_ANSWER, false);
            }
            if (getIntent().hasExtra(AppKey.QUESTION_ID)) {
                questionId = getIntent().getStringExtra(AppKey.QUESTION_ID);
            }
            if (getIntent().hasExtra(AppKey.QUESTION_TITLE)) {
                questionTitle = getIntent().getStringExtra(AppKey.QUESTION_TITLE);
            }
        }
        lsContent.setOnOpenUrlListener(new LSWebView.OnOpenUrlListener() {
            @Override
            public void onOpenUrl(String url) {

            }

            @Override
            public void showLoadingLayout() {

            }

            @Override
            public void hideLoadingLayout() {
                int height = (int) ((float) RT.getScreenHeight() / RT.getDensity()) - 300;
                lsContent.loadUrl("javascript:setDivHeight('" + height + "')");
                lsContent.loadUrl("javascript:getDivFocus()");
                if (isEditAnswer) {
                    String content = answer.getContent();
                    lsContent.loadUrl("javascript:htmls('" + content + "')");
                } else {
                    String hint = "写下你的回答";
                    lsContent.loadUrl("javascript:cue('" + hint + "')");
                }
                if (isEditProblem) {
                    String content = problem.getContent();
                    lsContent.loadUrl("javascript:htmls('" + content + "')");
                }
            }

            @Override
            public void onReceivedError() {

            }
        });
        if (isAnswer) {
            tvBack.setVisibility(View.VISIBLE);
            ibBack.setVisibility(View.GONE);
            tvSend.setText(R.string.publish);
//            et_rich.setHint("填写你的回答");
        } else {
            tvBack.setVisibility(View.GONE);
            ibBack.setVisibility(View.VISIBLE);
            tvSend.setText(R.string.nextToDo);
//            et_rich.setHint("请填写问题相关描述信息");
        }
    }

    EventListener eventListener = new EventListener() {
        @Override
        public void handleMessage(int what, int arg1, int arg2, Object dataobj) {
            switch (what) {
                case EventTag.ON_AT:
                    User user = (User) dataobj;
                    if (null != user && !TextUtils.isEmpty(user.getName())) {
//                        et_rich.addEditTextAtIndex(et_rich.getLastPosition(), "#" + user.getName() + "#");
                    }
                    break;
                case EventTag.ON_PROBLEM_ADD:
                    finish();
                    break;
                case EventTag.ON_GET_CONTENT:
                    InputContent values = (InputContent) dataobj;
                    String content = values.getContent();
                    String headImage = values.getHeadImage();
                    String inputText = values.getText();
                    if (TextUtils.isEmpty(inputText)) {
                        if (isAnswer) {
                            ToastUtil.showToast("回答不能为空！");
                        } else {
                            ToastUtil.showToast("问题描述不能为空！");
                        }
                        return;
                    }
                    if (isAnswer) {
                        if (inputText.length() > 30000) {
                            ToastUtil.showToast("回答不能超过30000字 ");
                            return;
                        }
                        if (isCanSend) {
                            isCanSend = false;
                            SoftKeyboardUtil.hideSoftKeyboard(lsContent);
                            postAnswer(content, headImage, isAnonymous);
                        }
                    } else {
                        if (inputText.length() > 500) {
                            ToastUtil.showToast("问题描述不能超过500字 ");
                            return;
                        }
                        if (isEditProblem) {
                            problem.setContent(content);
                            problem.setImage(headImage);
                            if (isAnonymous) {
                                problem.setIsAnonymous(1);
                            } else {
                                problem.setIsAnonymous(0);
                            }
                            SelectTopicActivity.startWithEditProblem(AnswerActivity.this, problem);
                        } else {
                            Intent intentSelectSubject = new Intent(AnswerActivity.this, SelectTopicActivity.class);
                            intentSelectSubject.putExtra(AppKey.QUESTION_TITLE, questionTitle);
                            intentSelectSubject.putExtra(AppKey.QUESTION_CONTENT, content);
                            intentSelectSubject.putExtra(AppKey.QUESTION_HEAD_IMAGE, headImage);
                            intentSelectSubject.putExtra(AppKey.IS_ANONYMOUS, isAnonymous);
                            startActivityForResult(intentSelectSubject, AppKey.REQUEST_CODE_PROBLEM_CONTENT);
                        }
                    }
                    break;
            }

        }
    };

    @Override
    public void initData() {

    }

    public void updateAnonymousUI() {
        if (isAnonymous) {
            ibAnonymous.setImageResource(R.drawable.ic_close_anonymous);
            tvAnonymousState.setText("关闭匿名");
        } else {
            ibAnonymous.setImageResource(R.drawable.ic_open_anonymous);
            tvAnonymousState.setText("启用匿名");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(TAG);
        EventManager.ins().removeListener(EventTag.ON_AT, eventListener);
        EventManager.ins().removeListener(EventTag.ON_GET_CONTENT, eventListener);
        EventManager.ins().removeListener(EventTag.ON_PROBLEM_ADD, eventListener);
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ibKeyboard:
                if (isKeyboardShow) {
                    SoftKeyboardUtil.hideSoftKeyboard(lsContent);
                } else {
                    SoftKeyboardUtil.showSoftKeyboard(lsContent);
                }
                break;
            case R.id.ibAt:
                Intent intent = new Intent(AnswerActivity.this, AtSomeOneActivity.class);
                startActivity(intent);
                break;
            case R.id.ib_picture:
                lsContent.loadUrl("javascript:ZSSEditor.restoreRange()");
                SoftKeyboardUtil.hideSoftKeyboard(lsContent);
                imagePicker.gallerySelectedPic(this);
                break;
            case R.id.tvSend:// 发送数据结构
                lsContent.loadUrl("javascript:getInputContents()");
                if (ClickUtil.isFastDoubleClick()) return;
                break;
            case R.id.tvBack:
            case R.id.ibBack:
                onBackPressed();
                break;
            case R.id.ibSetting:
                if (View.GONE == llActionBottom.getVisibility()) {
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, keyboardHeight);
                    llActionBottom.setLayoutParams(params);
                    llActionBottom.setVisibility(View.VISIBLE);
                    SoftKeyboardUtil.hideSoftKeyboard(lsContent);
                } else {
                    SoftKeyboardUtil.showSoftKeyboard(lsContent);
                    llActionBottom.setVisibility(View.GONE);
                }
                break;
            case R.id.ibAnonymous:
                if (isAnonymous) {
                    isAnonymous = false;
                    ibAnonymous.setImageResource(R.drawable.ic_close_anonymous);
                    tvAnonymousState.setText("关闭匿名");
                    ToastUtil.showToast("已关闭匿名");
                } else {
                    isAnonymous = true;
                    ibAnonymous.setImageResource(R.drawable.ic_open_anonymous);
                    tvAnonymousState.setText("启用匿名");
                    ToastUtil.showToast("已启用匿名");
                }
                break;
        }
    }

    boolean isKeyboardShow = false;

    private int keyboardHeight;

    @Override
    public void onKeyboardChange(boolean isShow, int keyboardHeight) {
        int height = (int) ((float) (RT.getScreenHeight() - 100 - keyboardHeight) / RT.getDensity());

        lsContent.loadUrl("javascript:setDivHeight('" + height + "')");
        isKeyboardShow = isShow;
        if (!isShow) {
            ibKeyboard.setImageResource(R.drawable.ic_keybord_show);
        } else {
            llActionBottom.setVisibility(View.GONE);
            if (keyboardHeight > 140) {
                this.keyboardHeight = keyboardHeight;
            }
            ibKeyboard.setImageResource(R.drawable.ic_keybord_hide);
        }
    }

    boolean isCanSend = true;//允许发送

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePickerManager.RESULT_CODE_ITEMS) {
            if (data == null) {
                return;
            }
            if (requestCode == ImagePickerManager.RESULT_CODE_GALLERY) {//从图库返回
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePickerManager.EXTRA_RESULT_ITEMS);
                for (int i = 0; i < images.size(); i++) {
                    ImageItem item = images.get(i);
                    insertBitmap(item.path);
                }
            }
        } else if (requestCode == ImagePickerManager.REQUEST_CODE_TAKE) {
            //发送广播通知图片增加了
            ImagePickerManager.galleryAddPic(this, imagePicker.getTakeImageFile());
            ImageItem imageItem = new ImageItem();
            imageItem.path = imagePicker.getTakeImageFile().getAbsolutePath();
            imagePicker.clearSelectedImages();
            imagePicker.addSelectedImageItem(0, imageItem, true);
            insertBitmap(imagePicker.getTakeImageFile().getAbsolutePath());
        } else if (resultCode == RESULT_OK) {
            if (requestCode == AppKey.REQUEST_CODE_PROBLEM_CONTENT) {
                setResult(RESULT_OK);
                finish();
            }
        }
    }

    /**
     * 发表回复
     *
     * @param answerContent
     * @param isAnonymous
     */
    private void postAnswer(String answerContent, String headImage, boolean isAnonymous) {
        showLoadingDialog();
        if (isEditAnswer) {
            API_Found.ins().modtifyAnswer(TAG, answer.getId(), answer.getProblemId(), answerContent, headImage, isAnonymous, new StringResponseCallback() {
                @Override
                public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                    hideLoadingDialog();
                    if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                        API_Statistics.ins().addActionData(TAG, AnswerActivity.this, AppKey.TYPE_ANSWER);
                        EventManager.ins().sendEvent(EventTag.ON_ANSWER_EDIT, 0, 0, null);
                        ToastUtil.showToast("修改成功！");
                        setResult(RESULT_OK);
                        finish();
                    } else if (ResponseResult.ResultStatus.BE_ADD_BLACK == errCode) {
                        ToastUtil.showToast("由于对方的设置，你不能回答此问题");
                    } else {
                        ToastUtil.showToast(errMsg);
                    }
                    return false;
                }
            });
        } else {
            API_Found.ins().publishAnswer(TAG, questionId, answerContent, headImage, isAnonymous, new StringResponseCallback() {
                @Override
                public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                    isCanSend = true;
                    hideLoadingDialog();
                    if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                        API_Statistics.ins().addActionData(TAG, AnswerActivity.this, AppKey.TYPE_ANSWER);
                        EventManager.ins().sendEvent(EventTag.ON_ANSWER_ADD, 0, 0, null);
                        ToastUtil.showToast("发送成功！");
                        setResult(RESULT_OK);
                        finish();
                    } else if (ResponseResult.ResultStatus.BE_ADD_BLACK == errCode) {
                        ToastUtil.showToast("由于对方的设置，你不能回答此问题");
                    } else {
                        ToastUtil.showToast(errMsg);
                    }
                    return false;
                }
            });
        }

    }

    /**
     * 添加图片到富文本剪辑器
     *
     * @param imagePath
     */
    private void insertBitmap(final String imagePath) {
        showLoadingDialog();
        API_App.ins().uploadData(TAG, imagePath, new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                hideLoadingDialog();
                if (errCode == ResponseResult.ResultStatus.OK) {
                    UploadResult result = new Gson().fromJson(resultValue, UploadResult.class);
                    if (null != result && null != result.getRes() && null != result.getRes().getHashmap()) {
                        String url = result.getRes().getHashmap().getImgurl();
                        lsContent.loadUrl("javascript:ZSSEditor.insertImage('" + url + "')");
                    }
                } else {
                    DLOG.e(TAG, errMsg);
                }
                return false;
            }
        });

    }


}
